/*
 ** StockDB
 **
 ** Copyright (C) 2012 - ? doublegsoft
 **
 ** This program is free software: you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License as published by
 ** the Free Software Foundation, either version 3 of the License, or
 ** (at your option) any later version.
 **
 ** This program is distributed in the hope that it will be useful,
 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 ** GNU General Public License for more details.
 **
 ** You should have received a copy of the GNU General Public License
 ** along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>

#ifdef WIN32

#include <winsock2.h>
#include <ws2tcpip.h>

#else

#include <netdb.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#endif // #ifdef WIN32

int
main()
{
  int sock, err;
  struct hostent *host;
  // connector’s address information
  struct sockaddr_in server;

#ifdef WIN32
  WSADATA wsadata;
  WSAStartup(0x0202, &wsadata);
  if ((err = WSAStartup(0x0202, &wsadata)) != 0)
  {
    fprintf(stderr, "WSAStartup() failed with error %d\n", err);
    WSACleanup();
    exit(1);
  }
#endif

  host = gethostbyname("127.0.0.1");
  printf("%s\n", host->h_name);

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock <= 0)
  {
    fprintf(stderr, "socket(): %s\n", strerror(sock));
    exit(-1);
  }

  memset(&server, '\0', sizeof(server));
  server.sin_family = AF_INET;
  server.sin_port = htons(7017);
  if (inet_pton(AF_INET, "127.0.0.1", &server.sin_addr) < 0)
  {
    fprintf(stderr, "inet_pton()");
    exit(-1);
  }
  // memcpy(&server.sin_addr, host->h_addr_list[0], sizeof(struct in_addr));

  err = connect(sock, (struct sockaddr *) &server, sizeof(struct sockaddr));
  if (err < 0)
  {
    fprintf(stderr, "connect(): %d - %s\n", err, strerror(err));
    exit(-1);
  }

  char *data = "~!@#$%^&*hello world*&^%$#@!~";
  err = send(sock, data, strlen(data), 0);
  if (err <= 0)
  {
    fprintf(stderr, "send(): %s\n", strerror(err));
    exit(-1);
  }

#ifdef WIN32
  closesocket(sock);
  WSACleanup();
#else
  close(sock);
#endif

  return 0;
}
